Total Complexity | 7 |
Total Lines | 58 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import { BEditaApiClient, ApiClientConfig } from './bedita-api-client'; |
||
2 | |||
3 | /** |
||
4 | * ApiProvider is responsible to create a `BEditaApiClient` and return the instance. |
||
5 | * |
||
6 | */ |
||
7 | export default class ApiProvider { |
||
8 | |||
9 | /** |
||
10 | * A map of clients created. |
||
11 | */ |
||
12 | static #registry: { [s: string]: BEditaApiClient } = {}; |
||
13 | |||
14 | /** |
||
15 | * Get an API client already created or try to create new one. |
||
16 | * If a client registered with `name` is found then returns it. |
||
17 | * |
||
18 | * @param name The name to use for register the API client |
||
19 | * @param config The configuration to use for create new client. |
||
20 | */ |
||
21 | public static get(name: string, config?: ApiClientConfig): BEditaApiClient { |
||
22 | if (this.has(name)) { |
||
23 | return this.#registry[name]; |
||
24 | } |
||
25 | |||
26 | if (!config || !config.baseUrl) { |
||
27 | throw new Error('Missing required API configuration'); |
||
28 | } |
||
29 | |||
30 | config.name = name; |
||
31 | this.#registry[name] = new BEditaApiClient(config); |
||
32 | |||
33 | return this.#registry[name]; |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * Return `true` if an API client with that `name` is in the registry. |
||
38 | * |
||
39 | * @param name The name of registered API client |
||
40 | */ |
||
41 | public static has(name: string): boolean { |
||
42 | if (this.#registry[name]) { |
||
43 | return true; |
||
44 | } |
||
45 | |||
46 | return false; |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * Remove an API client istance from the registry. |
||
51 | * |
||
52 | * @param name The name to look for in the registry |
||
53 | */ |
||
54 | public static remove(name: string): void { |
||
55 | if (!this.#registry[name]) { |
||
56 | return; |
||
57 | } |
||
58 | |||
59 | delete this.#registry[name]; |
||
60 | } |
||
62 |